// 路由管理
// 浏览器打开进行加载，一般只进行首页的加载
import {createRouter, createWebHistory, createWebHashHistory} from "vue-router"
import store from "@/store";
import api from "@/api";
import dayjs from "dayjs";

const routes = [
    {
        path: "/:*",
        component: () => import("@/components/home/home.vue"),
        meta: {title: '首页'}
    },
    {
        path: "/articleDetail",
        name: "articleDetail",
        component: () => import("@/components/articleEditing/ArticleDetail.vue"),
        meta: { title: '文章详情'}
    },
    {
        path: "/detail",
        name: "detail",
        component: () => import("@/components/detail/Detail.vue"),
        meta: { title: '文章详情'}
    },
    {
        path: "/blank",
        name: "blank",
        component: () => import("/src/components/detail/BlankPage.vue")
    },
    {
        path: "/community",
        name: "community",
        component: () => import("/src/components/community/community.vue"),
        meta: {title: '社区活动'}
    },
    {
        path: "/login",
        name: "login",
        component: () => import("@/components/signUpAndLogIn/Login.vue"),
        meta: {title: '登录'}
    },
    {
        path: "/topic",
        name: "topic",
        component: () => import("@/components/home/Topic.vue"),
    },
    {
        path: "/home",
        name: "home",
        component: () => import("@/components/home/home.vue"),
        meta: {title: '首页'},
    },

    {
        path: "/articleModifications",
        name: "articleModifications",
        component: () => import("@/components/articleEditing/ArticleModifications.vue"),
        meta: { title: '修改文章'},
    },
    {
        path: "/personalInformation",
        name: "PersonalInformation",
        component: () => import("@/components/PublicComponents/PersonalInformation.vue"),
        meta: {isAuth: true, title: '个人空间'},
        beforeEnter: (to, from, next) => {
            if (to.meta.isAuth) { //判断是否需要授权
                if (localStorage.getItem('user') !== null) {
                    next()  //放行
                } else {
                    return null;
                }
            } else {
                next()  //放行
            }
        }
    },
    {
        path: "/articleEditing",
        name: "articleEditing",
        component: () => import("@/components/articleEditing/ArticleEditing.vue"),
        meta: {isAuth: true, title: '我的创作'},
        beforeEnter: (to, from, next) => {
            if (to.meta.isAuth) { //判断是否需要授权
                if (localStorage.getItem('user') !== null) {
                    next()  //放行
                } else {
                    alert('抱歉，请先登录！')
                    next("/login");
                }
            } else {
                next()  //放行
            }
        }
    },
    {
        path: "/changelog",
        name: "changelog",
        component: () => import("@/components/changelog/Changelog.vue"),
        meta: { title: '更新公告'}
    },
    {
        path: "/greatPictures",
        name: "greatPictures",
        component: () => import("@/components/great/GreatPictures.vue"),
        meta: { title: '精美图片'}
    },
    {
        path: "/messageBoards",
        name: "messageBoards",
        component: () => import("@/components/MessageBoards/MessageBoards.vue"),
        meta: {title: '留言板'}
    },
    {
        path: "/loveSpace",
        name: "loveSpace",
        component: () => import("@/components/love/LoveSpace.vue"),
        meta: {title: '恋爱空间'}
    },
    {
        path: "/loveBlankPage",
        name: "loveBlankPage",
        component: () => import("@/components/love/LoveBlankPage.vue"),
    },
    {
        path: "/homeBlankPage",
        name: "HomeBlankPage",
        component: () => import("@/components/home/HomeBlankPage.vue")
    },

];
const router = createRouter({
    // createWebHashHistory()  不需要后端配合  类似于a标签的描点连接
    // history:createWebHistory(),
    history: createWebHashHistory(),
    routes,
});

// 全局导航守卫 (切换路由前)
router.beforeEach((to, from, next) => {
    if (to.path !== '/logout') {
        store.commit('LoadTheAnimation');
        setTimeout(() => {
            store.commit('LoadTheAnimation');
        }, 800)
    }
    //获取浏览器里存储的token
    const tokenStr = localStorage.getItem("AUTHORIZATION_TOKEN");//读取浏览器的token
    //没有token则应该删除用户的信息
    if (!tokenStr)
        localStorage.removeItem("user");

    let user = JSON.parse(window.localStorage.getItem("user"));
    if (user != null) {
        api.communicationGet(user.uid).then((res) => {
            if (res.data.code === 200) {
                window.localStorage.getItem("message");
                if (res.data.data.length > 0) {
                    window.localStorage.setItem("message", JSON.stringify(res.data.data));
                }
            }
        });
    }
    // to.path.startsWith  、表示该路径下的访问都要进行验证  包括子路由
    if(to.path==="/login"){
        store.commit('loginStatue',true);
    }else {
        store.commit('loginStatue',false);
    }
    api.getAdminWeb().then((res) => {
        window.localStorage.setItem("DataContent", JSON.stringify(res.data.data));
    })
    next();
})
// 全局导航守卫 (切换路由后)
router.afterEach((to, from) => {
    document.title = to.meta.title || '默认名'    //修改网页的title
    let date = new Date();
    let visit = window.localStorage.getItem("visitWeb");
    if (visit == null) {
        api.addWebLength().then((res) => {
            window.localStorage.setItem("visitWeb", dayjs(date).format("YYYY-MM-DD"));
        });
    } else {
        let now =window.localStorage.getItem("visitWeb");
        if (dayjs(date).format("YYYY-MM-DD") !== now) {
            api.addWebLength().then((res) => {
                window.localStorage.setItem("visitWeb", dayjs(date).format("YYYY-MM-DD"));
            });
        }
    }
    //页面跳转后回到顶部
     window.scrollTo(0,0);
})


export default router;